<script setup lang="ts">

import {onMounted, reactive, ref} from 'vue'
import type { VxeGridProps } from 'vxe-table'
import {deleteCompanyNo, queryCompanyNos, queryDatabasesApi, saveCompanyNo} from "../../../api/fastApi/fastApi";
import {layer} from "@layui/layer-vue";
import {CompanyNoVO} from "../../../untils/interfaceDefine";
import XEUtils from 'xe-utils';

const databases = ref([])
const gridRef = ref()
const targetName = ref('')
const tableAllData = ref([])

const gridOptions = reactive<VxeGridProps<CompanyNoVO>>({
  border: true,
  showOverflow: true,
  editConfig: {
    trigger: 'click',
    mode: 'cell'
  },
  height: 630,
  columns: [
    { type: 'seq', width: 70 },
    { field: 'company_no', title: '公司号', editRender: { name: 'input' } },
    { field: 'company_name', title: '公司名称', editRender: { name: 'input' } },
    { field: 'industry', title: '行业', editRender: { name: 'input' } },
    { field: 'db_type', title: '数据库类型', editRender: { name: 'input' } },
    { field: 'env_name', title: '环境名称', slots: { default: 'envName'} },
    { field: 'description', title: '描述', editRender: { name: 'input' } },
    { title: '操作', width: 200, slots: { default: 'operate' } }
  ],
  data: []
})


onMounted(()=>{
  queryDBS();
  fetchData();
})


const handleSearch = () => {
    const filterVal = XEUtils.toValueString(targetName.value).trim().toLowerCase()
    if (filterVal) {
        const filterRE = new RegExp(filterVal, 'gi')
        const options = { children: 'children' }
        const searchProps: any = ['company_no', 'company_name', 'industry', 'db_type', 'description']
        // 搜索为克隆数据，不会污染源数据
        gridOptions.data = XEUtils.searchTree(tableAllData.value, (item: any) => searchProps.some((key: string | number) =>
            String(item[key]).toLowerCase().indexOf(filterVal) > -1), options);
    } else {
        gridOptions.data = tableAllData.value
    }
}

// 节流函数,间隔500毫秒触发搜索
const searchEvent = XEUtils.throttle(function () {
    handleSearch()
}, 500, { trailing: true, leading: true })

const fetchData = async () => {
  await queryCompanyNos({}).then(res => {
    tableAllData.value = res.data;
    gridOptions.data = res.data;
  })
}


const saveRow = async (row: CompanyNoVO) => {
  await saveCompanyNo(row).then(res => {
    fetchData();
    layer.msg("更新成功！")
  })
}

const deleteRow = async (row: CompanyNoVO) => {
  layer.confirm('确定删除吗？', {
      btn: [
          {text:'确定', callback: (id) => {
              deleteCompanyNo({id: row.id}).then(res => {
                fetchData();
                layer.msg("删除成功！")
              })
              layer.close(id); }
          },
          {text:'取消', callback: (id) => {
              layer.close(id); }
          }
      ]
  });
}

const queryDBS = async () => {
    let response = await queryDatabasesApi({});
    if(response.status === 200){
        databases.value = response.result;
    }
}



const addEvent = async () => {
  const $grid = gridRef.value
  if ($grid) {
    const user_detail = localStorage.getItem("user_detail");
    const user_detail_json = JSON.parse(user_detail as string);
    const user = user_detail_json?.user_no;
    const currentDate = new Date()
    const formattedDate = currentDate.toLocaleDateString()
    const record = {
      id: null,
      product_id: 'AML5.0',
      company_no: '',
      company_name: '',
      industry: '',
      db_type: '',
      env_name: '',
      description: user + '新增|时间：' + formattedDate,
    }
    const { row: newRow } = await $grid.insertAt(record, -1);
    // 激活不自动聚焦
    await $grid.setEditRow(newRow)
  }
}
</script>

<template>
  <lay-card>
    <vxe-button status="primary" @click="addEvent" style="margin-bottom: 10px;">新增</vxe-button>
    <vxe-input v-model="targetName" placeholder="请输入公司号/名称" @input="searchEvent" style="margin-left: 25px;width: 300px"></vxe-input>
    <vxe-grid v-bind="gridOptions" ref="gridRef">
      <template #operate="{ row }">
        <vxe-button status="primary" content="保存" @click="saveRow(row)"></vxe-button>
        <vxe-button status="danger" content="删除" @click="deleteRow(row)"></vxe-button>
        </template>
      <template #envName="{ row }">
        <vxe-select v-model="row.env_name" transfer>
          <vxe-option :value="item.name" :label="item.title" v-for="item in databases"></vxe-option>
        </vxe-select>
      </template>
    </vxe-grid>
  </lay-card>
</template>

<style scoped>

</style>